package tree.easy;

import tree.TreeNode;

import java.util.*;

public class IsSymmetric {
    public static void main(String[] args) {
        IsSymmetric isSymmetric = new IsSymmetric();
        System.out.println(isSymmetric.isSymmetric(TreeNode.ROOT));
        List<Integer> list = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        System.out.println(list);
        System.out.println(list2);
    }

    /**
     * 广度优先算法
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Integer[] list = new Integer[size];
            Integer[] list2 = new Integer[size];
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll();
                if (treeNode != null) {
                    list[i] = treeNode.val;
                    list2[(size - 1) - i] = treeNode.val;
                    queue.offer(treeNode.left);
                    queue.offer(treeNode.right);
                } else {
                    list[i] = null;
                    list2[(size - 1) - i] = null;
                }
            }
            if (!Arrays.equals(list,list2)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 深度优先算法
     * @param root
     * @return
     */
    public boolean isSymmetric1(TreeNode root) {
        return check(root, root);
    }

    public boolean check(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
    }

}
